import router from './router'
import store from './store'
//import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { canTurnTo } from '@/utils/access'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

//const whiteList = ['/login'] // no redirect whitelist

const turnTo = (to, access, next) => {
  var can = canTurnTo(to.name, access, router.options.routes)
  if (can) next()//权限，可访问
  else next({ replace: true, name: 'error_401' })//无权限，重定向到401页面
}

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  //判断用户是否登录，登录了是否用户信息，用户名信息是否权限问跳转的路由
  const hasToken = getToken()//var hasLogin = 获取 token()

  if (hasToken) {
    if (to.path === '/login') {
      cz
      // if is logged in, redirect to the home page 登录后。试图重新跳转到应用首页
      next({ path: '/' })
      NProgress.done()
    } else {
      var userIfo = store.state.user.name
      if (userIfo) {
        turnTo(to, store.state.user.name, next)
      } else {
        console.log('登录成功，已经有token,但是还没有用户信息，准备用户名信息')
        store.dispatch('user/getInfo').then(user => {
          //拉取用户信息。通过用户权限和跳转的页面的nmae来判断是否权限访问
          //acces必须是一个数组，如：['super_adimn']['super_admin',''admin]
          turnTo(to, user.access, next)
          console.log(user.access)
        }).catch(() => {
          //获取用户信息失败，重置token
          store.dispatch('user')
          next('/')
        })
      }
    }
  } else {
    //没有登录(因为没有token)
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

//判断用户是否登录

var isLogin = 获取token()

if(isLogin){
  var hasUserInfo=获取用户信息()
  if(hasUserInfo){
    redirectTo(to,用户权限数组,next)//用户权限数组
  }else{
    去获取用户信息().then((res) =>{ 
      redirectTo(to,res.权限数组,next)//权限数组
    }).catch((res)=>{
      console.log(res)//输出
    })
  }
}else{
  next({path:'/long'})
}

// 用户信息 获取用户信息 (token){
//   返回用户信息
// }